package com.campusexpresspickup.controller;


import com.campusexpresspickup.service.IUserResourceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.campusexpresspickup.common.RestResponse;
import com.campusexpresspickup.component.DynamicSecurityMetadataSource;
import com.campusexpresspickup.entity.UserResource;
import com.campusexpresspickup.page.UserResourcePage;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 后台资源表 前端控制器
 * </p>
 *
 * @author lq
 * @since 2021-11-15
 */
@RestController
@RequestMapping("/user-resource")
public class UserResourceController {

  private final IUserResourceService resourceService;

  @Autowired
  private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;

  public UserResourceController(IUserResourceService resourceService) {
    this.resourceService = resourceService;
  }

  @PostMapping(value = "/create", name = "添加资源")
  public Object create(@RequestBody UserResource userResource) {
    int count;
    userResource.setCreateTime(LocalDateTime.now());
    if (userResource.getId() != null) {
      count = resourceService.getBaseMapper().updateById(userResource);
    } else {
      count = resourceService.getBaseMapper().insert(userResource);
    }
    dynamicSecurityMetadataSource.clearDataSource();
    if (count > 0) {
      return RestResponse.ok("创建成功");
    }
    return RestResponse.error("创建失败");
  }

  @GetMapping(value = "/{id}", name = "资源详情")
  public Object getResourceById(@PathVariable Integer id) {
    return RestResponse.ok(resourceService.getBaseMapper().selectById(id), "查询成功");
  }

  @PostMapping(value = "/list", name = "列表")
  public Object getResourceList(@RequestBody UserResourcePage userResourcePage) {
    PageHelper.startPage(userResourcePage.getPageStart(), userResourcePage.getPageSize());
    List<UserResource> userResourceList = resourceService.getUserResourceList(userResourcePage);
    return RestResponse.ok(new PageInfo<>(userResourceList), "查询成功");
  }

  @GetMapping(value = "/delete/{id}", name = "删除")
  public Object deleteResourceById(@PathVariable Integer id) {
    int delCount = resourceService.getBaseMapper().deleteById(id);
    if (delCount > 0) {
      RestResponse.ok("删除成功");
    }
    dynamicSecurityMetadataSource.clearDataSource();
    return RestResponse.error("删除失败");
  }
}
